import asyncio , os
import time

import aiohttp
import json

# 配置基础 URL
# BASE_URL = "http://localhost:8016"
BASE_URL = "http://localhost:18003"

async def test_neuttsAir( ):
    """测试启动推理服务"""
    # url = f"{BASE_URL}/experience/neuttsAir"
    url = f"{BASE_URL}/v1/audio/speech"

    print(url)
    data = {
        "input": "hello happy brithday",
        "voice": "dave",
        "model": "neuphonic/neutts-air"
    }

    async with aiohttp.ClientSession() as session:
        async with session.post(url, json=data) as response:

            # 检查响应状态
            if response.status == 200:
                # 获取文件名（如果响应头中有）
                content_disposition = response.headers.get('Content-Disposition', '')
                filename = 'stream_output.wav'
                if 'filename=' in content_disposition:
                    filename = content_disposition.split('filename=')[1].strip('"')

                # 创建输出目录
                output_dir = 'test_outputs'
                os.makedirs(output_dir, exist_ok=True)
                output_path = os.path.join(output_dir, filename)

                # 流式下载文件
                print(f"开始下载音频文件到: {output_path}")
                with open(output_path, 'wb') as f:
                    async for chunk in response.content.iter_chunked(1024 * 1024):  # 每次1MB
                        f.write(chunk)

                file_size = os.path.getsize(output_path)
                print(f"✓ 文件下载完成: {output_path}")
                print(f"✓ 文件大小: {file_size / 1024:.2f} KB")
            else:
                # 如果出错，打印错误信息
                error_text = await response.text()
                print(f"✗ 请求失败: {error_text}")

async def main():
    stateflag = await test_neuttsAir()

if __name__ == '__main__':
    asyncio.run(main())